package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.annotation.LoginRequire;
import com.example.nowcodercommunity.entity.Event;
import com.example.nowcodercommunity.entity.Page;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.event.EventProducer;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.FollowService;
import com.example.nowcodercommunity.service.UserService;
import com.example.nowcodercommunity.util.CommunityUtil;
import com.example.nowcodercommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class FollowController implements CommunityConstant{

    @Autowired
    private FollowService followService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    /**
     * 关注功能，必须登录后使用
     * @param entityType
     * @param entityId
     * @return
     */
    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequire
    public String follow(int entityType, int entityId){
        User user = hostHolder.getUser();
        followService.follow(user.getId(), entityType, entityId);

        // 触发事件
        Event event = new Event()
                .setUserId(user.getId())
                .setTopic(TOPIC_FOLLOW)
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);
        eventProducer.fireEvent(event);


        return CommunityUtil.getJSONString(0, "已关注!");
    }

    /**
     * 取消关注功能，必须登录后使用
     * @param entityType
     * @param entityId
     * @return
     */
    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    @LoginRequire
    public String unFollow(int entityType, int entityId){
        User user = hostHolder.getUser();

        followService.unFollow(user.getId(), entityType, entityId);

        return CommunityUtil.getJSONString(0, "已取消关注!");
    }

    /**
     * 查找用户关注列表
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    @LoginRequire
    public String getUserFollowee(@PathVariable(name = "userId") int userId, Page page, Model model){
        User host = hostHolder.getUser();
        model.addAttribute("user", host);
        User user = userService.findUserById(userId);

        if(user == null){
            throw new RuntimeException("该用户不存在");
        }

        page.setLimit(5);
        page.setSearchPath("/followee" + userId);
        page.setTotalRows((int) followService.getUserFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_USER));

        List<Map<String, Object>> userFollowee = followService.getUserFollowee(userId, page.getFrom(), page.getLimit());

        if(userFollowee != null){
            for(Map<String, Object> map:userFollowee){
                User followee = (User) map.get("user");
                boolean hasFollowed = followService.hasUserFollowedEntity(host.getId(), CommunityConstant.ENTITY_TYPE_USER, followee.getId());
                map.put("hasFollowed", hasFollowed);
            }
        }
        model.addAttribute("users", userFollowee);

        return "/site/followee";
    }

    /**
     * 查找用户关注者列表
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    @LoginRequire
    public String getUserFollower(@PathVariable(name = "userId") int userId, Page page, Model model){
        User host = hostHolder.getUser();
        model.addAttribute("user", host);
        User user = userService.findUserById(userId);

        if(user == null){
            throw new RuntimeException("该用户不存在");
        }

        page.setLimit(5);
        page.setSearchPath("/follower" + userId);
        page.setTotalRows((int) followService.getEntityFollowerCount(userId, CommunityConstant.ENTITY_TYPE_USER));

        List<Map<String, Object>> userFollower = followService.getUserFollowers(userId, page.getFrom(), page.getLimit());

        if(userFollower != null){
            for(Map<String, Object> map : userFollower){
                User follower = (User) map.get("user");
                boolean hasFollowed = followService.hasUserFollowedEntity(host.getId(), CommunityConstant.ENTITY_TYPE_USER, follower.getId());
                map.put("hasFollowed", hasFollowed);
            }
        }
        model.addAttribute("users", userFollower);

        return "/site/follower";
    }
}
